<?php

/**
* 随机换头像
* by torn
* 13.10.3
*/

ini_set('display_errors', 0);
define('MAXNUM', 600);
define('HEADER_URL', 'http://' . $_SERVER['SERVER_NAME'] . '/head/');//

$id = intval($_REQUEST['i']);
$type = $_REQUEST['t'];
new Imgdata($id, $type);

####### 图片获取&输出 类
class Imgdata {

	public $imgsrc;
	public $imgUrl;
    public $imgdata;
	public $imgform;

    public function __construct($id = 0, $type = 'r') {
		// type [r]photo resource [u]photo url
        $this->getImgName($id);
		$this->typeMode($type);
	}

	protected function typeMode($type = null) {
		$types = ['r' => 'imgByRandom', 's' => 'imgUrl', 'o' => 'oneImg', 'l' => 'listImg'];
		$typeArr = array_keys($types);
		$type = in_array($type, $typeArr) ? $type : $typeArr[0];
		$this->$types[$type]();
	}

	protected function getImgName($_num = 0) {
		$num = $_num > 0 && $_num <= MAXNUM ? $_num : mt_rand(1, MAXNUM);
		$head = $num . '.jpg';
		file_exists($head) || $head = '000.jpg';
		$this->imgsrc = $head;
		$this->imgUrl = HEADER_URL . $this->imgsrc;
	}

	protected function imgUrl() {
		header('Content-type: application/json');
		echo '{"error": 0, "msg": "success", "url": "' . $this->imgUrl . '"}';
	}

	protected function oneImg() {
		header('Location: ./' . $this->imgsrc);
	}

	protected function listImg() {
		$limit = intval($_GET['l']);
		$limit = $limit > 10 ? $limit : 10;
		$limit > 100 && $limit = 100;
		$imgHtml = '<style>img { margin: 5px; }</style>';
		for ($i = 0; $i < $limit; $i++) {
			$rand = mt_rand(1, MAXNUM);
			$head = $rand . '.jpg';
			if (!file_exists($head)) {
				--$i;
				continue;
			}
			$imgHtml .= '<img src="./' . $head . '" title="' . $rand . '" alt="' . $rand . '">';
		}

		header("Content-type: text/html; charset=utf-8"); 
		echo $imgHtml;
	}
	
	protected function imgByRandom() {
		$this->img2data();
		$this->data2img();
	}
	
    protected function img2data() {// 将图片数据读入
        $this->_imgfrom($this->imgsrc);// 取得文件类型 type
        //return $this->imgdata=fread(fopen($this->imgsrc,'rb'),filesize($this->imgsrc));
		return $this->imgdata = file_get_contents($this->imgsrc);
	}
	
    protected function data2img() {// 取出图片数据并输出浏览器
        $_GET['swt'] && file_put_contents("000.jpg", $this->imgdata);
        header("content-type:" . $this->imgform);
        echo $this->imgdata;
        //echo $this->imgform;
        //imagecreatefromstring($this->imgdata);
	}
	
    protected function _imgfrom($imgsrc) {
        $info = getimagesize($imgsrc);
        //var_dump($info);
        return $this->imgform = $info['mime'];
    }
}